import { sendMessage } from './socket'

// 房间状态管理
const roomState = {
  roomId: '',
  players: [],
  isOwner: false,
  gameStatus: 'waiting' // waiting/playing/ended
}

// 创建房间
export const createRoom = () => {
  return new Promise((resolve) => {
    uni.showLoading({ title: '创建房间中' })
    sendMessage('create-room')
    uni.$once('socket-room-created', data => {
      roomState.roomId = data.roomId
      roomState.isOwner = true
      uni.hideLoading()
      resolve(data.roomId)
    })
  })
}

// 加入房间
export const joinRoom = roomId => {
  return new Promise((resolve, reject) => {
    if (!roomId) return reject('无效的房间ID')
    
    uni.showLoading({ title: '加入房间中' })
    sendMessage('join-room', { roomId })
    
    uni.$once('socket-room-joined', data => {
      roomState.roomId = roomId
      roomState.players = data.players
      uni.hideLoading()
      resolve()
    })
    
    uni.$once('socket-error', msg => {
      uni.hideLoading()
      reject(msg || '加入失败')
    })
  })
}

// 更新玩家状态
uni.$on('socket-player-update', players => {
  roomState.players = players
  uni.$emit('players-updated', players)
})